package org.kiwi.job.web.interceptor;

import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;

/**
 * @email jack.liu.19910921@gmail.com
 * Created by jack on 17/2/13.
 */
public class PlatformSignInterceptor implements HandlerInterceptor {
    private final Logger logger = LoggerFactory.getLogger(PlatformSignInterceptor.class);

    private final static String SKIP_PATH_REGEX = "^/(_health_check|403|404|405|500)$";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            logger.info("-----------开始平台签名认证-------------");
            String servletPath = request.getServletPath();
            if (servletPath.matches(SKIP_PATH_REGEX)) {
                logger.info("健康检查页面跳过");
                return true;
            }
            if (0 == servletPath.indexOf("/healthCheck/")) {
                logger.info("业务健康检查页面跳过");
                return true;
            }


            String sign = request.getParameter("sign");
//             if (CommValidation.isEmpty(sign)) {
// //                writerToJson();
// //                return false;
//             }
            Map requestParams = request.getParameterMap();
            Map<String, Object> params = Maps.newHashMap();
            for (Iterator iterator = requestParams.keySet().iterator(); iterator.hasNext(); ) {
                String name = (String) iterator.next();
                String[] values = (String[]) requestParams.get(name);
                StringBuilder valueStr = new StringBuilder();
                for (int i = 0; i < values.length; i++) {
                    if (i == values.length - 1) {
                        valueStr.append(values[i]);
                    } else {
                        valueStr.append(values[i]).append(",");
                    }
                }
                params.put(name, valueStr);
            }
            // TODO: 17/2/13  验签
            return true;
        } catch (Exception e) {
            logger.error("校验签名异常", e);
            throw e;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("-----------{}-----请求完成-----------", request.getRequestURI());
    }

    // public void writerToJson(BaseResponse resp, HttpServletResponse response) {
    //     responseString(JSON.toJSONString(resp), response);
    // }

    public void responseString(String data, HttpServletResponse response) {
        response.setContentType("text/plain; charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(data);
        } catch (IOException e) {
            logger.error("response响应数据异常", e);
        } finally {
            if (pw != null) {
                pw.flush();
                pw.close();
            }
        }
    }
}
